<template>
  <view class="min-h-screen bg-[#f8f8f8] pb-[100rpx]">
    <!-- 顶部导航 -->
    <NavigationBar title="订单列表" />
    <!-- 顶部导航栏 -->
    <view class="bg-white shadow-sm px-[32rpx] pt-[20rpx] pb-[10rpx]">
      <view class="flex justify-between border-b border-[#f0f0f0] pb-[10rpx]">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="relative px-[20rpx] py-[16rpx] text-[28rpx] font-medium transition-all duration-200"
          :class="
            activeTab === tab.type
              ? 'text-[#AF6C31] border-b-2 border-[#AF6C31]'
              : 'text-[#666]'
          "
          @click="changeTab(tab.type)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      class="px-[20rpx] pt-[20rpx]"
      scroll-y="true"
      @refresherrefresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
    >
      <block v-if="orderList.length > 0">
        <view
          v-for="(order, index) in orderList"
          :key="index"
          class="bg-white rounded-[16rpx] mb-[24rpx] overflow-hidden shadow-sm order-card"
          @click="
            goToOrderDetail(
              order.id,
              order.status,
              order.masterId,
              order.isProject,
            )
          "
        >
          <!-- 订单头部 -->
          <view
            class="flex justify-between items-center p-[24rpx] border-b border-[#f5f5f5]"
          >
            <view
              class="text-[28rpx] text-[#333] font-medium flex items-center"
            >
              <view class="mr-[8rpx] text-[#AF6C31]">订单号：</view>
              <view style="font-size: 24rpx">{{ order.orderNo }}</view>
            </view>
            <view
              class="text-[24rpx] py-[6rpx] px-[16rpx] rounded-full"
              style="font-size: 24rpx"
              :class="getStatusClass(order.statusDesc)"
            >
              {{ order.statusDesc || getStatusText(order.status) }}
            </view>
          </view>

          <!-- 订单内容 -->
          <view class="flex p-[24rpx]">
            <image
              class="w-[160rpx] h-[160rpx] rounded-[12rpx] mr-[24rpx] border border-[#f0f0f0] bg-[#fafafa]"
              :src="
                upload_url + order.productCoverImgUrl ||
                '/static/default-image.png'
              "
              mode="aspectFill"
            ></image>
            <view class="flex-1">
              <view
                class="text-base text-[#121836] font-medium mb-[12rpx] line-clamp-2"
                >{{ order.productName || order.productName }}</view
              >
              <view class="text-base text-[#AF6C31] font-medium"
                >¥{{ Number(order.price).toFixed(2) }}</view
              >
              <view
                v-if="order.paymentMethod"
                class="text-sm text-[#999] mt-[4rpx]"
                >支付方式：{{ order.paymentMethod }}</view
              >
            </view>
          </view>

          <!-- 订单底部 -->
          <view
            class="flex justify-between items-center px-[24rpx] py-[16rpx] bg-[#fafafa]"
          >
            <view class="text-sm text-[#999]"
              >下单时间：{{ formatDate(order.createTime) }}</view
            >
            <view class="flex">
              <view
                v-if="order.status === 0"
                class="mr-[16rpx] py-[10rpx] px-[32rpx] bg-white border border-[#AF6C31] text-[#AF6C31] rounded-[30rpx] shadow-sm btn"
                style="font-size: 24rpx"
                @click.stop="handleCancelOrder(order.id)"
              >
                取消订单
              </view>
              <!-- <view
                v-if="order.status === 0"
                class="py-[10rpx] px-[32rpx] text-[24rpx] bg-gradient-to-r from-[#AF6C31] to-[#C98B5A] text-white rounded-[30rpx] shadow-sm btn"
                @click.stop="payOrder(order.id)"
              >
                去支付
              </view> -->
            </view>
          </view>
        </view>
      </block>

      <!-- 空状态 -->
      <up-empty
        v-if="orderList.length === 0 && !loading"
        mode="order"
        text="暂无订单数据"
        marginTop="100"
      ></up-empty>
      <!-- 加载中 -->
      <view
        v-if="loading && orderList.length === 0"
        class="flex justify-center items-center py-[80rpx]"
      >
        <view
          class="animate-spin rounded-full h-[60rpx] w-[60rpx] border-[6rpx] border-[#f3f3f3] border-t-[#AF6C31]"
        ></view>
        <view class="text-[28rpx] text-[#999] ml-[20rpx]">加载中...</view>
      </view>
      <!-- 加载更多 -->
      <view
        v-if="orderList.length > 0 && hasMore"
        class="text-center py-[30rpx] text-[24rpx] text-[#999]"
      >
        <view v-if="loading" class="flex justify-center items-center">
          <view
            class="animate-spin rounded-full h-[32rpx] w-[32rpx] border-[4rpx] border-[#f3f3f3] border-t-[#AF6C31] mr-[10rpx]"
          ></view>
          <view>加载中...</view>
        </view>
        <view v-else>上拉加载更多</view>
      </view>
      <view
        v-if="orderList.length > 0 && !hasMore"
        class="text-center py-[30rpx] text-[24rpx] text-[#999]"
      >
        没有更多数据了
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import NavigationBar from "@/components/navigationBar/index.vue";
import { ref, reactive, onMounted } from "vue";
import { onShow, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import { getOrderList, cancelOrder as apiCancelOrder } from "@/api/shop";
import { type OrderItem } from "@/api/shop";
import { upload_url } from "@/utils/config";

// 标签页
const tabs = [
  { name: "全部", type: "all" },
  { name: "待核销", type: "unfinished" },
  { name: "已完成", type: "finished" },
  { name: "已取消", type: "cancelled" },
];
const activeTab = ref("all");

// 订单列表
const orderList = ref<OrderItem[]>([]);
const pageNumber = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const refreshing = ref(false);

// 获取页面参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  // @ts-ignore - 兼容不同版本的uni-app
  const type = currentPage.options?.type || "all";

  activeTab.value = type;
  loadOrders();
});

// 页面显示时刷新数据
onShow(() => {
  refreshOrders();
});

// 监听上拉加载更多
onReachBottom(() => {
  if (hasMore.value && !loading.value) {
    pageNumber.value++;
    loadOrders();
  }
});

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  refreshOrders();
};

// 刷新订单
const refreshOrders = () => {
  pageNumber.value = 1;
  orderList.value = [];
  hasMore.value = true;
  loadOrders().then(() => {
    refreshing.value = false;
  });
};

// 切换标签页
const changeTab = (type: string) => {
  activeTab.value = type;
  pageNumber.value = 1;
  orderList.value = [];

  hasMore.value = true;
  loadOrders();
};

// 加载订单数据
const loadOrders = async () => {
  if (loading.value) return Promise.resolve();
  loading.value = true;

  // 根据activeTab值设置不同的状态查询
  let status;
  switch (activeTab.value) {
    case "unfinished":
      status = 0;
      break;
    case "finished":
      status = 1;
      break;
    case "cancelled":
      status = 2;
      break;
    default:
      status = null; // 全部订单不筛选status
  }
  try {
    // 调用获取订单列表API
    const res = await getOrderList({
      pageNumber: pageNumber.value,
      pageSize: pageSize.value,
      status,
    });

    if (res.code === 200) {
      if (pageNumber.value === 1) {
        orderList.value = res.data || [];
      } else {
        orderList.value = [...orderList.value, ...(res.data || [])];
      }
      hasMore.value = orderList.value.length < res.data.total;
    }
    return Promise.resolve();
  } catch (error) {
    loading.value = false;
    return Promise.reject(error);
  } finally {
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "待支付";
    case 1:
      return "待核销";
    case 2:
      return "已完成";
    case 3:
      return "已取消";
    default:
      return "未知状态";
  }
};

// 获取状态类样式
const getStatusClass = (statusDesc: string) => {
  switch (statusDesc) {
    case "待支付":
      return "text-[#FF9500] bg-[#FFF5E6]"; // 待支付 - 橙色
    case "待核销":
      return "text-[#AF6C31] bg-[#FBF2EA]"; // 待核销 - 主题棕色
    case "已完成":
      return "text-[#52C41A] bg-[#F6FFED]"; // 已完成 - 绿色
    case "已取消":
      return "text-[#999] bg-[#F5F5F5]"; // 已取消 - 灰色
    default:
      return "text-[#999] bg-[#F5F5F5]";
  }
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
};

// 跳转到订单详情
const goToOrderDetail = (
  id: number,
  status: number,
  masterId: number,
  isProject: number,
) => {
  if (status === 0) {
    uni.navigateTo({
      url: `/pages/home/successfully?id=${masterId}&isProduct=${isProject}`,
    });
  } else {
    uni.navigateTo({
      url: `/pages/my/orderDetail?id=${id}`,
    });
  }
};

// 取消订单
const handleCancelOrder = (id: number) => {
  uni.showModal({
    title: "提示",
    content: "确定要取消此订单吗？",
    success: (res) => {
      if (res.confirm) {
        console.log(id, "id");

        // 调用取消订单API
        apiCancelOrder(id)
          .then((res: any) => {
            if (res.code === 200) {
              uni.showToast({
                icon: "none",
                title: "订单已取消",
              });
              // 重新加载订单列表
              pageNumber.value = 1;
              loadOrders();
            } else {
              uni.showToast({
                title: res.message || "取消订单失败",
                icon: "none",
              });
            }
          })
          .catch(() => {
            uni.showToast({
              title: "取消订单失败",
              icon: "none",
            });
          });
      }
    },
  });
};

// 去支付
const payOrder = (id: number) => {
  uni.navigateTo({
    url: `/pages/payment/index?orderId=${id}`,
  });
};
</script>

<style>
/* 加载中动画 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 卡片悬浮效果 */
.order-card {
  transition: all 0.3s;
}

.order-card:active {
  transform: scale(0.99);
  opacity: 0.9;
}

/* 按钮点击效果 */
.btn {
  position: relative;
  overflow: hidden;
}

.btn:active::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.2);
}
</style>
